package labb1.fordjupn;

import labb1.del2.Card;

import java.util.Random;

/**
 * @author Mikko Puustinen (mikko.puustinen@gmail.com)
 * @version 0.1, 2007-nov-02
 */
public class InSeaGame extends GameFactory {
    private PlayerFactory playerFactory;

    public InSeaGame(PlayerFactory playerFactory) {
        super(playerFactory);
        this.playerFactory = playerFactory;
    }

    /**
     * Checks if the current Player has four Cards with the same value and
     * removes them from the Player and adds points.
     *
     * @return true if the current Player has four cards with the same value.
     */
    public boolean hasFourOfAKind() {
        Player current = getCurrentPlayer();
        boolean isFour = false;

        for (int i = 1; i <= 13; i++) {
            if (current.numberOfSameValues(i) == 4) {
                for (Card c : current.getAllCards()) {
                    if (c.getValue() == i)
                        current.getCard(c);
                }
                if (current.getAllCards().size() == 0)
                    takeCardFromDeck(getIndexOfCurrentPlayer());
                current.addScore(4);
                isFour = true;
            }
        }

        if (isFour && current.getNoOfCard() == 0)
            takeCardFromDeck(getIndexOfCurrentPlayer());
        return isFour;
    }

    /**
     * Selects randomly which opponent to select.
     *
     * @return the opponent to take a Card from. This will NOT be the current
     *         player.
     */
    public int randomOpponent() {
        Random ran = new Random();
        int currentPlayer = getIndexOfCurrentPlayer();
        int opponent = currentPlayer;
        int random = -1;

        while (opponent == currentPlayer) {
            while ((random = ran.nextInt()) < 0) {
            }
            opponent = random % playerFactory.numberOfPlayers();
        }

        return opponent;
    }

    /**
     * Selects a random index in the current player's list of cards.
     *
     * @return a card value. This will ONLY be a value which is in the current
     *         player's list of cards.
     */
    public int randomValue() {
        Random ran = new Random();
        int index;
        int random = -1;

        while ((random = ran.nextInt()) < 0) {
        }

        index = random % getCurrentPlayer().getNoOfCard();

        return getCurrentPlayer().showCard(index).getValue();
    }
}
